package com.choupin.choupin.service.impl;

import com.choupin.choupin.entity.Prize;
import com.choupin.choupin.mapper.LotterypoolMapper;
import com.choupin.choupin.service.IPrizeService;
import com.choupin.choupin.service.exception.ParameterIsEmptyException;
import com.choupin.choupin.service.exception.SelectExcepion;
import com.choupin.choupin.service.exception.UpdateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service

public class PrizeImpl implements IPrizeService {

    @Autowired
    LotterypoolMapper  lotterypoolMapper;

    @Override
    public List<Prize> showPrize(String phone,Integer currentPage,Integer pagePize) {
//        参数校验
        if (phone==null){
            throw new ParameterIsEmptyException("参数为空");
        }
        List<Prize> list=lotterypoolMapper.selectAllUserPrize(phone,currentPage,pagePize);
//        获取当前时间
        LocalDateTime localDateTime=LocalDateTime.now();
//        检测是否有奖品过期
        for(Prize p:list){
            if (localDateTime.isAfter(p.getEndTime())){
//                奖品过期
                Integer result=lotterypoolMapper.updatePrizeOneId(p.getId(),3);
                if (result==null){
                    throw new SelectExcepion("更新奖品状态失败！");
                }
                System.out.println("更新过期奖品成功！");
//                重新查询数据返回
                list=lotterypoolMapper.selectAllUserPrize(phone,currentPage,pagePize);
            }
        }

        if (list==null||list.size()<=0){
            throw new SelectExcepion("查询错误！");
        }
        return list;
    }

    @Override
    public void updatePrize(Integer id) {
//        参数校验
        if (id==null){
            throw  new ParameterIsEmptyException("参数为空！");
        }
        Integer result=lotterypoolMapper.updatePrizeOneId(id,1);
        if (result==null||result!=1){
            throw new UpdateException("更新状态失败！");
        }
        System.out.println("奖品兑换成功！");
    }
}
